#include "chatwidget.h"
#include "ui_chatwidget.h"

ChatWidget::ChatWidget(QWidget *parent, IcySettings *fSettings,
                       const QString &sfSN, const QString &sfAlias) :
    QWidget(parent),
    ui(new Ui::ChatWidget)
{
    ui->setupUi(this);
    settings = fSettings;

    sSN = new QString(sfSN);
    sAlias = new QString(sfAlias);

    ui->sendBtn->setText(tr("Send"));
    ui->sendBtn->setIcon(settings->getIcon("system://sendbtn"));

    ui->actionSend->setShortcutContext(Qt::WindowShortcut);
    ui->textEdit->addAction(ui->actionSend);
}

ChatWidget::~ChatWidget()
{
    delete ui;
}

void ChatWidget::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
        case QEvent::LanguageChange:
            ui->retranslateUi(this);
            break;

        default:
            break;
    }
}

_fastcall void ChatWidget::addEvent(const QString &sEvent)
{
    if ( sEvent.trimmed().endsWith("br>", Qt::CaseInsensitive) )
        ui->textBrowser->append(sEvent);
    else
        ui->textBrowser->append(sEvent + "<br>");
}

void ChatWidget::sendMsg()
{
    if ( ui->textEdit->toPlainText().trimmed().isEmpty() )
        return;

    QString sText("<font color=blue><b>");
    sText.append(*sAlias + " [" + QDateTime::currentDateTime().toString("dd-MM-yyyy hh:mm:ss"));
    sText.append("]</b></font><br>" + ui->textEdit->toHtml());
    addEvent(sText);

    emit onSendMsg(*sSN, ui->textEdit->toPlainText());
    ui->textEdit->clear();
}

/*************************************************
        SLOTS
*************************************************/

void ChatWidget::on_sendBtn_clicked()
{
    sendMsg();
}

void ChatWidget::onMsgReceived(const QString &sMessage)
{
    QString sText("<font color=red><b>");
    sText.append(*sAlias + " [" + QDateTime::currentDateTime().toString("dd-MM-yyyy hh:mm:ss"));
    sText.append("]</b></font><br>" + sMessage);
    addEvent(sText);
}

void ChatWidget::onXStatusChanged(const QString &sHead, const QString &sText)
{
    QString sfText("<font color=red><b>");
    sfText.append(sHead + "  " + sfText);
    sfText.append("</b></font>");
    addEvent(sfText);
}

void ChatWidget::on_actionSend_triggered()
{
    sendMsg();
}
